<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			*{
				padding: 0;
				margin: 0;
			}
			.drag{
				position: absolute;
				left: 0;
				width: 100px;
				height: 100px;
			}
			.drag1{
				background: red;
			}
			.drag2{
				left: 100px;
				background: blue;
			}
		</style>
	</head>
	<body>
		<div class="drag drag1"></div>
		<div class="drag drag2">限定范围 拖拽</div>
		<script type="text/javascript">
			function isObject(obj){
				return toString.call(obj) ==='[object Object]'
			}
			function isArray(){
				return toString.call(obj) === '[object Array]'
			}
			function deepCopy(obj){
				let newObj = {}
				for(let key in obj){
					if(obj.hasOwnProperty(key)){
						if(isObject(obj[key])){
							newObj[key] = deepCopy(obj[key])
						}else{
							newObj[key] = obj[key]
						}
					}
				}
				return newObj
			}
		</script>
		<script type="text/javascript">
			function Drag(el){
				this.el = document.querySelector(el)
				this.current = {
					x:0,
					y:0
				}
				this.downFn()
				
			}
			Drag.prototype.downFn = function(){
				this.el.addEventListener('mousedown',(e)=>{
					e.preventDefault()
					this.current.x = e.clientX-this.el.offsetLeft
					this.current.y = e.clientY-this.el.offsetTop
					this.dragMove()
					this.dragUp()
				})
			}
			Drag.prototype.dragMove = function(){
				document.onmousemove =(e)=>{
					var offsetX = e.clientX - this.current.x
					var offsetY = e.clientY - this.current.y
					this.setStyle(offsetX,offsetY)
				}
			}
			Drag.prototype.dragUp = function(){
				document.onmouseup = function(){
					document.onmousemove = null;
					document.onmouseup = null;
				}
			}
			Drag.prototype.setStyle = function(x,y){
				this.el.style.left = x+'px'
				this.el.style.top = y+'px'
			}
			var drag1 = new Drag('.drag1')
			
			
			
			// 限定范围 拖拽
			function DragLimit(el){
				Drag.call(this,el)
			}
			DragLimit.prototype = deepCopy(Drag.prototype)
			DragLimit.prototype.setStyle = function(x,y){
				if(x<0){x=0}
				if(y<0){y=0}
				this.el.style.left = x+'px'
				this.el.style.top = y+'px'
			}
			var drag2 = new DragLimit('.drag2')
		</script>
	</body>
</html>
